import postAnswer from "@/services/answer";
import { NextApiRequest, NextApiResponse } from "next";

function genAnswerInfo(reqBody: any = {}) {
  const answerList: any[] = [];
  Object.keys(reqBody).forEach((k) => {
    if (k !== "questionId") {
      answerList.push({
        componentId: k,
        value: reqBody[k],
      });
    }
  });

  return {
    questionId: reqBody.questionId,
    answerList,
  };
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== "POST")
    return res.status(200).json({ code: 1, msg: "method error" });
  const { questionId, answerList } = genAnswerInfo(req.body);
  const {
    code,
    message = "",
    result,
  } = await postAnswer(questionId, answerList);
  if (code > 0) {
    return res.redirect(
      `/fail${message ? "?message=" + encodeURI(message) : ""}`
    );
  }
  res.redirect(
    `/success${
      result ? "?questionId=" + result.questionId + "&answerId=" + result.answerId : ""
    }`
  );
}
